#### Script to do multiple treeMI imputations for the hardwood flooring industry
### and export the imputed dataset

#### input files:
####	flrf_gooddata_alt.csv
####
#### output files:
####    flr_imputes.csv
####    flr_predicted.csv

require(tree)


## Using alternative version of floordata without the year 1997 observations (which will get dropped in the exit regressions anyway).
flr_gooddata<-read.csv("flrf_gooddata_alt.csv",header=TRUE)

### Create completed datasets using treeMI:

flr_imputes<-treeMI(flr_gooddata,ITER=10,c(1,0,0,0,0,0,0,0,1,0,0,0,0,0),starter=TRUE,PPDdraw = TRUE, minCut = 5,minDev  = 0.00001, startCut = 5, startDev = 0.0001) 

flr_imputes$impSet$impsetnum <- 1
flr_imputes$PPDsample$impsetnum <- 1

### For the first imputed dataset, create a new file
write.table(flr_imputes$impSet,   file="flr_imputes.csv",append=FALSE,sep=",") 
write.table(flr_imputes$PPDsample,file="flr_predicted.csv",append=FALSE,sep=",") 

for (j in 2:500) {

  flr_imputes<-treeMI(flr_gooddata,ITER=10,c(1,0,0,0,0,0,0,0,1,0,0,0,0,0),starter=TRUE,PPDdraw = TRUE, minCut = 5,minDev  = 0.00001, startCut = 5, startDev = 0.0001) 

  flr_imputes$impSet$impsetnum <- j
  flr_imputes$PPDsample$impsetnum <- j

  ### Append the subsequent imputed datasets to the file created for the first dataset

  write.table(flr_imputes$impSet,   file="flr_imputes.csv",append=TRUE,sep=",",col.names=FALSE) 
  write.table(flr_imputes$PPDsample,file="flr_predicted.csv",append=TRUE,sep=",",col.names=FALSE) 

}


